const express = require('express')
const router = express.Router()
const userDb = require('../db/user-db')
const checkToken = require('../utils/checkToken')
const {logI} = require('../log')
const checkType = require('../utils/checkType')
const checkDeviceNo = require('../utils/checkDeviceNo')
const {retError, retSuccess} = require('../utils/ret')
const moment = require('moment')

router
    .post('/', async(req, res) => {
        let {body: {maddr,token,name,deviceNo}} = req
        logI('A-S', maddr, 'update_user_info', `${JSON.stringify(req.body)}`, 'null');
        try{
            const error = checkType.updateUserInfo(req.body)
            if(error){
                retError("update_user_info",maddr, 10001,  error.details[0].message, res);
            }else{
                let msg = {};
                msg = await checkToken(token,maddr);
                if(msg.code === 0){
                    const deviceInfo={
                        'maddr':maddr,
                        'deviceNo':deviceNo
                    }
                    let device={};
                    device = await checkDeviceNo(deviceInfo);
                    if(device.code === 0){
                        const time = moment().format('YYYY-MM-DD HH:mm:ss');
                        await userDb.updateUserInfo(name,time,maddr);
                        retSuccess("update_user_info", maddr,0, "", res);
                    }else{
                        retError("update_user_info", maddr,device.code, device.body, res);
                    }
                }else{
                    retError("update_user_info", maddr,msg.code, msg.body, res);
                }
            }
        } catch (e) {
            retError("update_user_info", maddr,10001, e, res);
        }
    })
module.exports = router
